<template>
  <div id="firmware-slit">
    <div class="search-box">
      <Row type='flex' justify="space-between" align='middle'>
        <Row type='flex' align='middle'>
          <Col class="search-item">
            <span class="sign"></span>
          </Col>
          <Col class="search-item sign1"><span>{{this.$route.query.shopName}}</span></Col>
        </Row>
        <Col class="search-item">
          <Button style="margin-right:24px" @click="allSet">批量设置</Button>
        </Col>
      </Row>
      <Row type='flex' align='middle'>
        <Col class="search-item"><span>机台名称：</span><Input placeholder="请输入" v-model='machineName' style="width:180px" :maxlength='20' /></Col>
        <Col class="search-item">
          <span>机台分类：</span>
          <Select v-model="machineType" @on-change="doSearch">
            <Option v-for="item in machineTypeList" :value="item.machineCategoryId" :key="item.machineCategoryId">{{ item.name }}</Option>
          </Select>
        </Col>
        <Col class="search-item">
          <span>执行状态：</span>
          <Select v-model="operationStatus" @on-change="doSearch">
            <Option v-for="item in operationStatusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col class="search-item">
          <Button type="primary" class="draw-btn" @click="doSearch">查询</Button>
        </Col>
        <Col class="search-item">
          <Button class="draw-btn" @click="reset">重置</Button>
        </Col>
      </Row>
    </div>
    <Table :columns="columns" :data="tableData" class="table-list table-show" :height='getTableHeight' :loading='loading'>
      <template slot-scope="{ row }" slot="exeStatus">
        <span>{{ row.exeStatus === 0 ? '未下载':row.exeStatus === 1? '未安装': row.exeStatus === 2?'已安装':'' }}</span>
      </template>
      <template slot-scope="{ row }"
                  slot="action">
          <i class="iconsys iconsetting" @click="setSlit('1',row)"
            title="设置"></i>
          <i class="iconsys iconzhongqi" @click="reStart(row)"
            title="重启"></i>
            <i class="iconsys iconlishijilu" @click="setSlit('2',row)"
              title="历史记录"></i>
        </template>
    </Table>
    <Row type='flex' justify="end" style="padding:20px">
      <Col>
        <Page :total="pageObj.total"
            :current="pageObj.pageIndex"
            :page-size="pageObj.pageSize"
            show-sizer
            show-total
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <!-- 选择机台组件 -->
    <select-shop :checkdList="checkdList" :titleObj='titleObj'
      :dataTree="dataTree"
      :modalShow="modalShow"
      @oncancel="selctshopCancel"
      @selctshop="volumeSet"
      v-if="modalShow">
    </select-shop>
    <Modal
        v-model="setModalStatus"
        :transfer='false'
         :closable='true'
         :mask-closable='false'
         @on-cancel="cancelModal"
        title="设置配置项">
        <Row>
          <Col>
            <Form ref="firmwareFormValidate" :model="firmwareFormValidate" :rules="firmwareRuleValidate" :label-width="100">
              <FormItem label="目标版本：" prop="firmwareVersion">
                <Select v-model="firmwareFormValidate.firmwareVersion" style="width:260px">
                  <Option v-for="item in versionList" :value="item" :key="item">{{ item }}</Option>
                </Select>
              </FormItem>
            </Form>
          </Col>
        </Row>
        <div slot="footer">
          <Button style="margin-right:10px;width:80px" @click="skipPrevious">上一步</Button>
          <Button type="primary" style='width:80px' @click="allMachineSet">确定</Button>
        </div>
    </Modal>
    <Drawer :title="drawTitle" :closable="true" width='640' :transfer='false' v-model="openDraw" class="history-draw">
      <Row type='flex' justify="center" style="padding-top:50px;border-top: 1px solid #e8eaec;" v-if="drawTitle === '固件升级设置'">
        <Col>
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
            <FormItem label="机台名称：" prop="machineName">
              <Input placeholder="机台名称" v-model='formValidate.machineName' style="width:260px" :disabled='true' />
            </FormItem>
            <FormItem label="投币口：" prop="slit">
              <Input placeholder="投币口" v-model='formValidate.slit' style="width:260px" :disabled='true' />
            </FormItem>
            <FormItem label="起始版本：" prop="firmwareStart">
              <Input placeholder="起始版本" v-model='formValidate.firmwareStart' style="width:260px" :disabled='true' />
            </FormItem>
            <FormItem label="目标版本：" prop="firmwareTarget">
              <!-- <Input placeholder="目标版本号" v-model='formValidate.firmwareTarget' style="width:260px" /> -->
              <Select v-model="formValidate.firmwareTarget" style="width:260px">
                <Option v-for="item in versionList" :value="item" :key="item">{{ item }}</Option>
              </Select>
            </FormItem>
          </Form>
        </Col>
      </Row>
      <div v-if="drawTitle === '历史记录'">
        <Table stripe :columns="columnsHistory" :data="tableHistoryData" :height='getHistoryHeight' class="table-list"></Table>
      </div>
      <div class="demo-drawer-footer">
        <Row type='flex' justify="end" v-if="drawTitle === '历史记录'">
          <Col>
          <Page :total="historyObj.total"
              :current="historyObj.pageIndex"
              :page-size="historyObj.pageSize"
              show-sizer
              show-total
              @on-change='changeHistoryPageIndex'
              @on-page-size-change='changeHistoryPageSize' />
          </Col>
        </Row>
        <div v-if="drawTitle === '固件升级设置'">
          <Button style="margin-right: 20px" class="draw-btn" @click="openDraw = false">取消</Button>
          <Button type="primary" class="draw-btn" @click="sureSet">确定</Button>
        </div>
      </div>
    </Drawer>
  </div>
</template>

<script>
import { slitFirmwareList, iterationHistoryList, lookTargetFirmware, setSlitPort } from '@/api/setting'
import SelectShop from '@/view/components/select-machine/select-machine.vue'
import machine from '@/view/setting/components/own-use/machine'
import mixins from '@/view/setting/components/own-use/mixins'
export default {
  name: 'firmware_slit',
  mixins: [mixins, machine],
  components: {
    SelectShop
  },
  computed: {
    getTableHeight () {
      let height = this.tableData.length > 10 ? 520 : 0
      return height
    },
    getHistoryHeight () {
      let height = 0
      if (this.tableHistoryData.length > 10) {
        height = (document.documentElement.clientHeight || document.body.clientHeight) - 103
      } else {
        height = 0
      }
      return height
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.queryShopId !== to.query.shopId || vm.queryType !== to.query.type) {
        vm.queryShopId = to.query.shopId
        vm.queryType = to.query.type
        vm.operationStatus = to.query.type === '0' ? '3' : ''
        vm.machineName = ''
        vm.machineType = ''
        vm.pageObj.pageIndex = 1
        vm.pageObj.pageSize = 10
        vm.getData()
      }
    })
  },
  data () {
    return {
      queryShopId: '',
      queryType: '',
      drawTitle: '固件升级设置',
      openDraw: false,
      loading: true,
      machineName: '',
      machineType: '',
      operationStatus: '',
      tableData: [],
      tableHistoryData: [],
      versionList: [], // 设置门店之后，需要选择的版本列表
      operationStatusList: [
        { value: '0', label: '未下载' },
        { value: '1', label: '未安装' },
        { value: '2', label: '已安装' },
        { value: '3', label: '未升级' } // 包含未下载及未安装
      ],
      formValidate: {
        machineName: '',
        slit: '',
        firmwareStart: '',
        firmwareTarget: ''
      },
      ruleValidate: {
        firmwareTarget: { required: true, message: '目标版本不能为空', trigger: 'change' }
      },
      firmwareFormValidate: {
        firmwareVersion: ''
      },
      firmwareRuleValidate: {
        firmwareVersion: { required: true, message: '目标版本不能为空', trigger: 'change' }
      },
      columnsHistory: [
        {
          title: '发布时间',
          key: 'createTime',
          width: 150
        },
        {
          title: ' 起始版本',
          key: 'extra'
        },
        {
          title: '目标版本',
          key: 'configValue'
        },
        // {
        //   title: '返回状态',
        //   key: 'status'
        // },
        {
          title: '操作人',
          key: 'creatorName',
          width: 160
        }
      ],
      columns: [
        {
          title: '机台名称',
          key: 'machineInstanceName'
        },
        {
          title: ' 投币口名称',
          key: 'machineInstanceSoltCode'
        },
        {
          title: '机台分类',
          key: 'categoryName'
        },
        {
          title: '当前版本',
          key: 'currentVersion'
        },
        {
          title: '目标版本',
          key: 'configValue'
        },
        {
          title: '返回状态',
          slot: 'exeStatus'
        },
        {
          title: '操作时间',
          key: 'operTime'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ]
    }
  },
  methods: {
    volumeSet (val) {
      this.setModalStatus = true
      this.modalShow = false
      this.checkdList = val
      this.getTargetList()
    },
    allMachineSet () {
      this.$refs.firmwareFormValidate.validate((valid) => {
        if (valid) {
          let arr = this.checkdList.map(item => {
            return item.machineInstanceId
          })
          setSlitPort({
            merchantId: this.$store.state.user.merchantId,
            type: 2,
            belongIdArray: arr,
            configKey: 'targetFirmwareVersion',
            configValue: this.firmwareFormValidate.firmwareVersion,
            creatorId: this.$store.state.user.userId,
            creatorName: this.$store.state.user.userName,
            extra: ''
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('设置成功！')
              this.setModalStatus = false
              this.getData()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    changeHistoryPageIndex (index) {
      this.historyObj.pageIndex = index
      this.getHistoryList()
    },
    changeHistoryPageSize (size) {
      this.historyObj.pageSize = size
      this.historyObj.pageIndex = 1
      this.getHistoryList()
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    doSearch () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    setSlit (type, row) {
      this.openDraw = true
      this.belongId = row.machineInstanceSoltId
      if (type === '2') {
        this.drawTitle = '历史记录'
        this.getHistoryList()
      } else if (type === '1') {
        this.drawTitle = '固件升级设置'
        this.getTargetList()
        this.formValidate.machineName = row.machineInstanceName
        this.formValidate.slit = row.machineInstanceSoltCode
        this.formValidate.firmwareStart = row.currentVersion
        // if ((row.configValue !== '0' || row.configValue !== 0) && row.configValue) {
        //   this.formValidate.firmwareTarget = row.configValue
        // }
        lookTargetFirmware().then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            this.versionList = result.data || []
            let target = ''
            if (this.versionList.length > 0) {
              if (row.configValue && (row.configValue !== '0' || row.configValue !== 0)) {
                target = row.configValue
              }
              this.versionList.forEach(ele => {
                if (ele === target) {
                  this.formValidate.firmwareTarget = target
                }
              })
            }
          } else {
            this.$Message.error(`${result.error}`)
          }
        })
      }
    },
    sureSet () {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          setSlitPort({
            merchantId: this.$store.state.user.merchantId,
            type: 1,
            belongIdArray: [this.belongId],
            configKey: 'targetFirmwareVersion',
            configValue: this.formValidate.firmwareTarget,
            creatorId: this.$store.state.user.userId,
            creatorName: this.$store.state.user.userName,
            extra: ''
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('设置成功！')
              this.openDraw = false
              this.getData()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    // 获取目标版本列表
    getTargetList () {
      lookTargetFirmware().then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.versionList = result.data || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    // 获取历史记录
    getHistoryList () {
      iterationHistoryList({
        merchantId: this.$store.state.user.merchantId,
        belongId: this.belongId,
        configKey: 'targetFirmwareVersion',
        offset: this.historyObj.pageSize * (this.historyObj.pageIndex - 1),
        limit: this.historyObj.pageSize
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.tableHistoryData = result.data || []
          this.historyObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    // 获取固件列表
    getData () {
      this.loading = true
      slitFirmwareList({
        merchantId: this.$store.state.user.merchantId,
        shopName: this.$route.query.shopName,
        shopId: this.$route.query.shopId,
        machineName: this.machineName, // 机台名称
        machineCategoryId: this.machineType, // 分类ID
        state: this.operationStatus, // 更新状态 0：未下载，1：未安装，2：已安装
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data || []
          this.pageObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    }
  },
  created () {
    this.queryShopId = this.$route.query.shopId
    this.queryType = this.$route.query.type
    this.operationStatus = this.$route.query.type === '0' ? '3' : ''
    this.getMachineList()
  },
  mounted () {
    this.getData()
  }
}
</script>

<style lang='less'>
  #firmware-slit {
    .draw-btn{
        width: 80px;
      }
    .search-box{
      .sign{
        display: block;
        width:8px;
        height: 20px;
        background: #2D8CF0;
      }
      .sign1{
        margin-left: 10px;
      }
    }
    .table-show {
      .animation-img{
        padding: 10px 0;
        img{
          width: 90px;
          height: 60px;
          display: block;
        }
      }
    }
    .ivu-drawer-body {
      padding: 0;
    }
    .ivu-drawer-header {
      border-bottom: 0;
    }
    .demo-drawer-footer {
      width: 100%;
      position: absolute;
      bottom: 0;
      right: 0;
      border-top: 1px solid #e8e8e8;
      padding: 10px 16px;
      text-align: right;
      background: #fff;
    }
  }
</style>
